package cn.chenc.framework.security.exception;

import cn.chenc.framework.core.consts.HttpStatus;
import cn.chenc.framework.core.model.response.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 　@description: TODO
 * 　@author secret
 * 　@date 2021/4/2 14:54
 *
 */
@RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SecurityExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(SecurityExceptionHandler.class);

    @ExceptionHandler(AccessDeniedException.class)
    public ResponseResult handleAuthorizationException(AccessDeniedException e) {
        log.error(e.getMessage());
        return ResponseResult.error(HttpStatus.FORBIDDEN, "没有权限，请联系管理员授权");
    }

    @ExceptionHandler(AccountExpiredException.class)
    public ResponseResult handleAccountExpiredException(AccountExpiredException e) {
        log.error(e.getMessage(), e);
        return ResponseResult.error(e.getMessage());
    }

    @ExceptionHandler(UsernameNotFoundException.class)
    public ResponseResult handleUsernameNotFoundException(UsernameNotFoundException e) {
        log.error(e.getMessage(), e);
        return ResponseResult.error(e.getMessage());
    }

}
